<template>
  <el-menu
  class="nav-menu"
  mode="horizontal"
  :default-active="currentPath"
  router
  active-text-color="red">
    <el-menu-item v-for="(item, i) in navList" :key="i" :index="item.name.toString()">
        {{item.navItem}}
    </el-menu-item>
    <i class="el-icon-s-promotion" @click="logout" style="float:right;font-size: 40px;color: #222;padding: 10px"></i>
  </el-menu>
</template>

<script>
import {createRouter} from '../../router'
export default {
  name: 'NavMenu',
  data () {
    return {
      // currentURL: '',
      navList: [
        { name: '/index', navItem: '首页' },
        { name: '/jotter', navItem: '笔记本' },
        { name: '/library', navItem: '图书馆' },
        { name: '/music', navItem: '音乐中心' },
        { name: '/admin', navItem: '个人中心' }
      ]
    }
  },
  computed: {
    currentPath () {
      var x = this.$route.path.indexOf('/', 1)
      if (x !== -1) {
        return this.$route.path.substring(0, x)
      } else {
        return this.$route.path
      }
    }
  },
  methods: {
    // 登出
    logout () {
      var _this = this
      this.$confirm('确定退出当前用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.get('/logout').then(resp => {
          if (resp.data.code === 200) {
            // 前后端状态保持一致
            _this.$store.commit('logout')
            _this.$router.replace('/login')
            // 清空adminMenus
            _this.$store.state.adminMenus = []
            // 清空路由，防止路由重复加载
            const newRouter = createRouter()
            _this.$router.matcher = newRouter.matcher
          }
        })
      }).catch(() => {
        // element-ui消息提示
        this.$message({
          type: 'info',
          message: '取消/登出失败！'
        })
      })
    }
  }
}
</script>

<style scoped>
  a{
    text-decoration: none;
  }
  span {
    pointer-events: none;
  }
  .el-icon-s-promotion {
    cursor: pointer;
    outline:0;
  }
</style>
